// 检查会话状态
use webrtc::peer_connection::RTCPeerConnection;
use webrtc::peer_connection::peer_connection_state::RTCPeerConnectionState;
use std::sync::{atomic::AtomicBool, Arc, Mutex};
use tokio::time::{sleep, Duration};
use once_cell::sync::Lazy;
use std::sync::atomic::Ordering;

// 默认为true, 连接断开后设置为false
// 确保xbox端主动断开的时候, 接收端能及时感知到并主动断开会话
pub static PEER_CONNECTION_STATUS: Lazy<Arc<AtomicBool>> = Lazy::new(|| Arc::new(AtomicBool::new(true)));
pub async fn check_status(peer_connection: &RTCPeerConnection) {
    let status = Arc::new(Mutex::new(false));
    let status_clone = status.clone();
    peer_connection.on_peer_connection_state_change(Box::new(move |state| {
        println!("🔍 PeerConnection 状态变化: {:?}", state);
        match state {
            RTCPeerConnectionState::Closed => {
                println!("🚪 连接已关闭");
            }
            RTCPeerConnectionState::Disconnected => {
                println!("🔌 连接断开");
                PEER_CONNECTION_STATUS.store(false, Ordering::SeqCst);
            }
            RTCPeerConnectionState::Failed => {
                println!("❌ 连接失败");
            }
            RTCPeerConnectionState::Connected => {
                println!("🔗 连接成功");
                *status_clone.lock().unwrap() = true;
            }
            RTCPeerConnectionState::Connecting => {
                println!("🔄 连接中");
            }
            RTCPeerConnectionState::New => {
                println!("🔄 初始化中");
            }
            RTCPeerConnectionState::Unspecified => {
                println!("🔄 未定义状态");
            }
        }
        return Box::pin(async {});
    }));
    loop {
        if(*status.lock().unwrap()){
            println!("🔗 连接成功");
            break;
        }
        // 避免异步阻塞
        sleep(Duration::from_millis(500)).await;
    }
}